//
//  THJDataDetailVC.m
//  THJXHW
//
//  Created by 河南德艺 on 2017/9/15.
//  Copyright © 2017年 河南德艺. All rights reserved.
//

#import "THJDataDetailVC.h"
#import "THJTitleInfoCell.h"
#import "THJChartViewCell.h"
#import "THJChangeBtnCell.h"
#import "THJAboutChartCell.h"
#import "THJSArticleCell.h"
#import <SDAutoLayout.h>
#import "THJWebviewVC.h"
#import "THJZxTitleCell.h"
#import "THJPortDataVC.h"
#import "THJInvitationDataVC.h"
#import "THJSlagsVC.h"
#import "THJGetMoreNewsController.h"
#import "THJZiXunInfoCell.h"
#import "ZBNetworking.h"
#import "THJHistoryDataCell.h"
#import "THJHistoryDataTitleCell.h"
#import "THJOtherDataCell.h"
#import "THJQihuoIndexVC.h"
#import "THJGuessPriceVC.h"
#import "THJNewsDetailVC.h"
@interface THJDataDetailVC ()<UITableViewDelegate,UITableViewDataSource,THJChangeBtnCellDelegate,THJChartViewCellDelegate,THJOtherDataCellDelegate>
{
    NSInteger _dayLength;
    UITableView * _tableview;
    NSInteger changeBtnIndex;
    NSArray * newDataArr;
    NSArray * newDateArr;
    NSArray * titleArr;
    NSString * urlType;
}
@property(nonatomic,strong)NSArray * dataArr;
@property(nonatomic,strong)NSArray * dateArr;
@property(nonatomic,strong)NSArray * areaArr;
@property(nonatomic,strong)NSArray * newsArr;
//历史数据数组
@property(nonatomic,strong)NSArray * historyArr;
//相关数据数组
@property(nonatomic,strong)NSArray * otherDataArr;
@property(nonatomic,assign)NSInteger hiPrice;
@property(nonatomic,assign)NSInteger lowPrice;
@property(nonatomic,assign)NSInteger max;
@property(nonatomic,assign)NSInteger maxChangn;
@property(nonatomic,assign)NSInteger min;
@property(nonatomic,assign)NSInteger minChangn;
@end

@implementation THJDataDetailVC
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.tabBarController.tabBar.hidden = YES;

    [self.navigationController.navigationBar setTitleTextAttributes:
     @{NSFontAttributeName:[UIFont systemFontOfSize:12],

       NSForegroundColorAttributeName:[UIColor whiteColor]}];

}
-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
}
/**
 查看更多新闻
 */
-(void)getMoreNewsAction{
    THJGetMoreNewsController * vc = [THJGetMoreNewsController new];
    vc.urlType = urlType;
    [self.navigationController pushViewController:vc animated:YES];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.view.backgroundColor = COLOR(34, 34, 34, 1);
    changeBtnIndex = 1;
    _dayLength = 7;
    [self loadDataWithType:self.itemType Area:self.areaId];
    [self loadHistoryDataWithType:self.itemType Area:self.areaId];
    [self loadOtherDataWithType:self.itemType];
    [self setupTableview];
    //获取新闻的类型
    if([self.titleStr containsString:@"硅铁"]){
        urlType = @"硅铁";
    }else if ([self.titleStr containsString:@"硅锰"]){
        urlType = @"硅锰";
    }else if ([self.titleStr containsString:@"铬铁"]){
        urlType = @"铬铁";
    }else if ([self.titleStr containsString:@"金属硅"]){
        urlType = @"金属硅";
    }
    [self getNewsWithType:urlType Page:@"1"];
    
    if(KIsiPhoneX){
         [self setSelfNavBarWithTitle:[NSString stringWithFormat:@"更新时间：%@",self.updateTime]];
    }else{
        [self setNavBarWithTitle:[NSString stringWithFormat:@"更新时间：%@",self.updateTime]];
    }
//    [self update];
}
/**
 定制导航栏
 */
-(void)setSelfNavBarWithTitle:(NSString*)title{
    UIView * view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, 84)];
    view.backgroundColor = COLOR(83, 84, 85, 1);
    [self.view addSubview:view];
    
    UIButton * btn = [UIButton buttonWithType:UIButtonTypeSystem];
    btn.frame = CGRectMake(15, 50, 24, 24);
    [btn setBackgroundImage:kGetImage(@"返回") forState:UIControlStateNormal];
    [btn addTarget:self action:@selector(pop) forControlEvents:UIControlEventTouchUpInside];
    [view addSubview:btn];
    
    UILabel * lab = [[UILabel alloc] initWithFrame:CGRectMake((ScreenWidth-150)/2, 52, 150, 21)];
    lab.textColor = SingleColor(whiteColor);
    lab.textAlignment = NSTextAlignmentCenter;
    lab.font = [UIFont systemFontOfSize:12];
    [view addSubview:lab];
    lab.text = title;
    
    UIButton * shareBtn = [UIButton buttonWithType:UIButtonTypeSystem];
    shareBtn.frame =CGRectMake(ScreenWidth - 40, 46, 25, 25);
    
    [shareBtn setBackgroundImage:kGetImage(@"zhishuShare") forState:UIControlStateNormal];
    [shareBtn addTarget:self action:@selector(shareBtnAction) forControlEvents:UIControlEventTouchUpInside];
    [view addSubview:shareBtn];
}
-(void)setNavBarWithTitle:(NSString*)title{
    UIView * view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, 64)];
    view.backgroundColor = COLOR(83, 84, 85, 1);
    [self.view addSubview:view];
    
    
    UIButton * btn = [UIButton buttonWithType:UIButtonTypeSystem];
    btn.frame = CGRectMake(15, 30, 24, 24);
    [btn setBackgroundImage:kGetImage(@"返回") forState:UIControlStateNormal];
    [btn addTarget:self action:@selector(pop) forControlEvents:UIControlEventTouchUpInside];
    [view addSubview:btn];
    
    
    UILabel * lab = [[UILabel alloc] initWithFrame:CGRectMake((ScreenWidth-150)/2, 30, 150, 21)];
    lab.textColor = SingleColor(whiteColor);
    lab.font = [UIFont systemFontOfSize:12];
    lab.textAlignment = NSTextAlignmentCenter;
    [view addSubview:lab];
    lab.text = title;
    
    UIButton * shareBtn = [UIButton buttonWithType:UIButtonTypeSystem];
    shareBtn.frame =CGRectMake(ScreenWidth - 40, 30, 25, 25);
    
    [shareBtn setBackgroundImage:kGetImage(@"zhishuShare") forState:UIControlStateNormal];
    [shareBtn addTarget:self action:@selector(shareBtnAction) forControlEvents:UIControlEventTouchUpInside];
    [view addSubview:shareBtn];
    
}
-(void)shareBtnAction{
    NSString * url = [NSString stringWithFormat:@"http://bigdata.thjb.net/dist/#/chart/phonecellDetail/%@/%@",self.itemType,self.areaId];
     NSLog(@"fenxiang-%@",url);
    NSString * title = [NSString stringWithFormat:@"%@地区%@%@合金宝指数",self.dataInfo[@"name"],self.updateTime,self.titleStr];
    NSLog(@"%@-%@",self.dataInfo,self.itemType);
    NSString * content = [NSString stringWithFormat:@"铁合金现货网%@%@地区%@价格(数据来自合金宝)",self.updateTime,self.dataInfo[@"name"],self.titleStr];
    NSLog(@"content-url-%@",url);
    [self shareWithContent:content Title:title Url:url];
}
/**
    THJChangeBtnDeletate  资讯 、历史、相关
 */
-(void)changeBtnClickedWith:(NSInteger)index{
    if(changeBtnIndex != index){
        changeBtnIndex = index;
        [_tableview reloadData];
    }
}
/**
 THJChartViewCellDelegate
 @param index 1 周 2 一月 3 三月
 */
-(void)changeMonthBtnclick:(NSInteger)index{
    if (index == 1) {
        _dayLength = 7;
    }else if (index == 2){
        _dayLength = 30;
    }else if (index == 3){
        _dayLength = 59;
    }
    [self subArrWithLength:_dayLength];
}
-(void)setupTableview{
    _tableview = [[UITableView alloc] initWithFrame:CGRectMake(0, 84, ScreenWidth, ScreenHeight-84) style:UITableViewStylePlain];
    [_tableview registerNib:[UINib nibWithNibName:@"THJTitleInfoCell" bundle:nil] forCellReuseIdentifier:@"cell1"];
    [_tableview registerNib:[UINib nibWithNibName:@"THJChartViewCell" bundle:nil] forCellReuseIdentifier:@"cell2"];
    [_tableview registerNib:[UINib nibWithNibName:@"THJChangeBtnCell" bundle:nil] forCellReuseIdentifier:@"cell3"];
    [_tableview registerNib:[UINib nibWithNibName:@"THJAboutChartCell" bundle:nil] forCellReuseIdentifier:@"cell4"];
    [_tableview registerNib:[UINib nibWithNibName:@"THJZiXunInfoCell" bundle:nil] forCellReuseIdentifier:@"cell5"];
    [_tableview registerNib:[UINib nibWithNibName:@"THJZxTitleCell" bundle:nil] forCellReuseIdentifier:@"zxcell"];
    [_tableview registerNib:[UINib nibWithNibName:@"THJHistoryDataCell" bundle:nil] forCellReuseIdentifier:@"hisdata"];
    [_tableview registerNib:[UINib nibWithNibName:@"THJHistoryDataTitleCell" bundle:nil] forCellReuseIdentifier:@"histitle"];
    [_tableview registerNib:[UINib nibWithNibName:@"THJOtherDataCell" bundle:nil] forCellReuseIdentifier:@"other"];
    _tableview.backgroundColor = COLOR(34, 34, 34, 1);
    _tableview.delegate = self;
    _tableview.dataSource = self;
    _tableview.separatorInset = UIEdgeInsetsMake(0, 0, 0, 0);
    [_tableview  setSeparatorColor:COLOR(77, 77,77, 1)];
    _tableview.showsVerticalScrollIndicator = NO;
    _tableview.tableFooterView = [UIView new];
    [self.view addSubview:_tableview];
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    NSInteger index = indexPath.row;
    if (index == 0) {
        return 140;
    }else if (index == 1){
         return 265;
    }else if (index == 2){
        return 43;
    }else{
        if (changeBtnIndex == 1) {
            return 65;
        }else if(changeBtnIndex == 3){
            NSInteger count = self.otherDataArr.count;
            if(count<=4 && count>0){
                count = 1;
            }else if(count>4 && count<=8){
                count = 2;
            }else if(count>8 && count<=12){
                count = 3;
            }else{
                count = 4;
            }
            return count * (ScreenWidth/4);
        }else{
            return 44;
        }
    }
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (changeBtnIndex == 1) {
        return self.newsArr.count+3;
    }else if(changeBtnIndex == 2){
        return self.historyArr.count + 4;
    }else{
        return 4;
    }
}
-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.row == 0) {
        THJTitleInfoCell * cell1 = [tableView dequeueReusableCellWithIdentifier:@"cell1" forIndexPath:indexPath];
//        cell1.dic = self.dataInfo;
        [cell1 updateCellContentWith:self.dataInfo Type:self.titleStr];
        cell1.highPrice.text = [NSString stringWithFormat:@"%ld(%ld)",self.max,self.maxChangn];
        cell1.lowPrice.text = [NSString stringWithFormat:@"%ld(%ld)",self.min,self.minChangn];
        cell1.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell1;
    }else if (indexPath.row == 1){
        THJChartViewCell * cell2 = [tableView dequeueReusableCellWithIdentifier:@"cell2" forIndexPath:indexPath];
        cell2.delegate = self;
        [cell2 setchartViewData:newDataArr DateArr:newDateArr highPrice:self.hiPrice lowPrice:self.lowPrice];
        cell2.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell2;
    }else if (indexPath.row == 2){
        THJChangeBtnCell * cell3 = [tableView dequeueReusableCellWithIdentifier:@"cell3" forIndexPath:indexPath];
        cell3.selectionStyle = UITableViewCellSelectionStyleNone;
        cell3.delegate = self;
        return cell3;
    }else{
        if(changeBtnIndex == 1){
            NSDictionary * dic = self.newsArr[indexPath.row-3];
            THJZiXunInfoCell * cell3 = [tableView dequeueReusableCellWithIdentifier:@"cell5" forIndexPath:indexPath];
            cell3.titleLab.text = dic[@"title"];
//            NSLog(@"%@",dic[@"addtime"]);
            cell3.timeLab.text = dic[@"addtime"];
            cell3.selectionStyle = UITableViewCellSelectionStyleNone;
            return cell3;
        }else if(changeBtnIndex == 2){
            if(indexPath.row == 3){
                THJHistoryDataTitleCell * cell = [tableView dequeueReusableCellWithIdentifier:@"histitle" forIndexPath:indexPath];
                cell.selectionStyle = UITableViewCellSelectionStyleNone;
                return cell;
            }else{
                NSDictionary * dic = self.historyArr[indexPath.row - 4];
                THJHistoryDataCell * cell = [tableView dequeueReusableCellWithIdentifier:@"hisdata" forIndexPath:indexPath];
                cell.selectionStyle = UITableViewCellSelectionStyleNone;
                [cell setContentWithDic:dic];
                return cell;
            }
        }else{
            THJOtherDataCell * cell = [tableView dequeueReusableCellWithIdentifier:@"other" forIndexPath:indexPath];
            cell.delegate = self;
            [cell setContentWithArr:self.otherDataArr];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            return cell;
        }
    }
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if(changeBtnIndex == 1){
        if(indexPath.row>2){
            NSDictionary * dic = self.newsArr[indexPath.row-3];
            THJNewsDetailVC * vc = [THJNewsDetailVC new];
            vc.itemid = dic[@"itemid"];
            vc.url = [NSString stringWithFormat:@"http://bigdata.thjb.net/dist/#/information/phoneinfodetail/21/%@",dic[@"itemid"]];
            vc.newsTitle = dic[@"title"];
            vc.newsContent = dic[@"introduce"];
            vc.mid = @"21";
            [self.navigationController pushViewController:vc animated:YES];
        }
    }
}
/**
 thjothercellDelegate

 @param Btnid id
 */
-(void)btnClickWithID:(NSInteger)Btnid{
    if(Btnid == 3 ||  Btnid == 5){
        THJPortDataVC * vc = [THJPortDataVC new];
        if(Btnid == 3){
            vc.dataType = @"price";
            vc.url = @"http://read.thjb.net/index.php?action=app_data_gk_price&type=1";
            vc.pageTitle = @"港口";
            vc.yDistance = @(95);
        }else{
            vc.url = @"http://read.thjb.net/index.php?action=app_data_gkkc&type=1";
            vc.dataType  =@"value";
            vc.yDistance = @(45);
            vc.pageTitle = @"库存量";
        }
        [self.navigationController pushViewController:vc animated:YES];
    }else if(Btnid == 6 || Btnid == 13 || Btnid == 11){
        THJInvitationDataVC * vc = [THJInvitationDataVC new];
        if(Btnid == 6){
            vc.getTypeUrl = @"http://read.thjb.net/index.php?action=zbprice_1_type";
            vc.getDataUrl = @"http://read.thjb.net/index.php?action=zbprice_1&type=";
            vc.title = @"招标价";
        }else if(Btnid == 13){
            vc.getTypeUrl = @"http://read.thjb.net/index.php?action=gkkczb_1_type";
            vc.getDataUrl = @"http://read.thjb.net/index.php?action=gkkczb_1_info&type=";
            vc.pageTitle = @"库存占比";
        }else{
            vc.getTypeUrl = @"http://read.thjb.net/index.php?action=xhl_1_type";
            vc.getDataUrl = @"http://read.thjb.net/index.php?action=xhl_1_info&type=";
            vc.pageTitle = @"消耗量";
        }
        [self.navigationController pushViewController:vc animated:YES];
    }else if(Btnid == 9 || Btnid == 4 || Btnid == 10 || Btnid == 7 || Btnid == 12 || Btnid == 8 ){
        THJSlagsVC * vc = [THJSlagsVC new];
        if (Btnid == 9) {
            vc.para2 = @"price";
            vc.para1 = @"name";
            vc.pageTitle = @"富锰渣价格";
            vc.url = @"http://read.thjb.net/index.php?action=fmzprice_1_info";
        }else if (Btnid == 4){
            vc.pageTitle = @"外盘";
            vc.type = @"waipan";
            vc.url = @"http://read.thjb.net/index.php?action=app_data_wp_price&type=1";
        }else if (Btnid == 7){
            vc.url = @"http://read.thjb.net/index.php?action=app_data_dj";
            vc.pageTitle = @"电价";
        }else if(Btnid == 10){
            vc.para2 = @"operation";
            vc.para1 = @"city";
            vc.pageTitle = @"开工率";
            vc.url = @"http://read.thjb.net/index.php?action=gmkgl_1_info";
        }else if(Btnid == 12){
            vc.pageTitle = @"产量";
            vc.url = @"http://read.thjb.net/index.php?action=cl_1_info";
        }else{
            vc.pageTitle = @"焦炭价格";
            vc.url = @"http://read.thjb.net/index.php?action=jtprice_1_info";
        }
        [self.navigationController pushViewController:vc animated:YES];
    }else if ( Btnid == 1){
        THJQihuoIndexVC * vc = [THJQihuoIndexVC new];
        vc.typeStr = self.itemType;
        [self.navigationController pushViewController:vc animated:YES];
    }else if ( Btnid == 2){
        THJGuessPriceVC * vc = [THJGuessPriceVC new];
        vc.type = self.itemType;
        [self.navigationController pushViewController:vc animated:YES];
    }

}
/**
 获取表格数据

 @param type 类型
 @param area 地区
 */
-(void)loadDataWithType:(NSString*)type Area:(NSString*)area{
    [MBProgressHUD showMessage:@"正在加载" toView:self.view];
    __weak typeof(self) weakself = self;
    [ZBRequestManager requestWithConfig:^(ZBURLRequest *request){
        request.urlString=[NSString stringWithFormat:@"http://read.thjb.net/index.php?action=app_hjb_list&area=%@&type=%@",area,type];
        NSLog(@"sj-url--%@",request.urlString);
        request.apiType=ZBRequestTypeCache;
    }  success:^(id responseObject,apiType type){
        NSDictionary * receiveData = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        [MBProgressHUD hideHUDForView:weakself.view animated:YES];
        if([receiveData[@"status"] isEqual:@"success"]){
            NSDictionary  * dataDic = receiveData[@"data"];
            weakself.dataArr = dataDic[@"priceList"];
            weakself.dateArr = dataDic[@"dataList"];
            self.hiPrice = [dataDic[@"max"] integerValue];
            self.lowPrice = [dataDic[@"min"] integerValue];
            [weakself subArrWithLength:_dayLength];
        }
    } failed:^(NSError *error){
    }];
}
/**
 获取历史数据
 
 @param type 类型
 @param area 地区
 */
-(void)loadHistoryDataWithType:(NSString*)type Area:(NSString*)area{
    [MBProgressHUD showMessage:@"正在加载" toView:self.view];
    __weak typeof(self) weakself = self;
    [ZBRequestManager requestWithConfig:^(ZBURLRequest *request){
        request.urlString=[NSString stringWithFormat:@"http://read.thjb.net/index.php?action=app_hjb_info&area=%@&type=%@",area,type];
        NSLog(@"history-url--%@",request.urlString);
        request.apiType=ZBRequestTypeCache;
    }  success:^(id responseObject,apiType type){
        NSDictionary * receiveData = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        [MBProgressHUD hideHUDForView:weakself.view animated:YES];
        if([receiveData[@"status"] isEqual:@"success"]){
            NSDictionary  * dataDic = receiveData[@"data"];
            weakself.max = [dataDic[@"max"] integerValue];
            weakself.min = [dataDic[@"min"] integerValue];
            weakself.maxChangn = [dataDic[@"max_change_n"] integerValue];
            weakself.minChangn = [dataDic[@"min_change_n"] integerValue];
            weakself.historyArr = dataDic[@"list"];
//            [_tableview reloadData];
        }
    } failed:^(NSError *error){
        
    }];
}
/**
 获取相关数据标题
 */
-(void)loadOtherDataWithType:(NSString*)type{
    [MBProgressHUD showMessage:@"正在加载" toView:self.view];
    __weak typeof(self) weakself = self;
    [ZBRequestManager requestWithConfig:^(ZBURLRequest *request){
        request.urlString= [NSString stringWithFormat:@"http://read.thjb.net/index.php?action=app_data_type&type=%@",type];
        NSLog(@"history-url--%@",request.urlString);
        request.apiType=ZBRequestTypeCache;
    }  success:^(id responseObject,apiType type){
        NSDictionary * receiveData = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        [MBProgressHUD hideHUDForView:weakself.view animated:YES];
        if([receiveData[@"status"] isEqual:@"success"]){
            weakself.otherDataArr = receiveData[@"data"];
        }
    } failed:^(NSError *error){
        
    }];
}
/**
 获取不tong类型的新闻
 @param type 新闻类型
 @param page 页数
 */
-(void)getNewsWithType:(NSString*)type Page:(NSString*)page{
    [MBProgressHUD showMessage:@"正在加载" toView:self.view];
    __weak typeof(self) weakself = self;
    NSString * urlStr = [NSString stringWithFormat:@"%@index.php?f=article&r=article&m=so&type=21&key=%@",THJUrlDomain,type] ;
    //stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSLog(@"指数资讯-%@",urlStr);
    [ZBRequestManager requestWithConfig:^(ZBURLRequest *request){
        request.urlString= urlStr;
        request.apiType=ZBRequestTypeRefresh;
    }  success:^(id responseObject,apiType type){
        NSDictionary * receiveData = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        [MBProgressHUD hideHUDForView:weakself.view animated:YES];
        NSLog(@"数组count-%@",receiveData);
        if([receiveData[@"status"] isEqual:@"200"]){
            weakself.newsArr = receiveData[@"data"];
            [_tableview reloadData];
        }
    } failed:^(NSError *error){
    }];
}
#pragma mark -- 截取数组绘图表
-(void)subArrWithLength:(NSInteger)length{
    NSInteger dataCount = self.dataArr.count;
    NSInteger dateCount = self.dateArr.count;
    NSArray * arr1 = self.dataArr;
    NSArray * arr2 = self.dateArr;
    NSLog(@"CC-%ld-%ld",dataCount,dateCount);
    if(_dayLength == 59){
        _dayLength = dataCount;
    } 
    newDataArr = [[[arr1 reverseObjectEnumerator] allObjects] subarrayWithRange:NSMakeRange(0, _dayLength)];
    newDateArr = [[[arr2 reverseObjectEnumerator] allObjects] subarrayWithRange:NSMakeRange(0, _dayLength)];
    [_tableview reloadData];
}
@end
